package pers.jason.wppm.auth.api.validate;

import org.apache.commons.lang.StringUtils;
import pers.jason.wppm.auth.api.enums.EnumVerifiable;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName: EnumInValidator
 * @Author: JZH
 * @Date: 2018/12/25 10:52
 *
 * 枚举校验器
 */
public class EnumInValidator implements ConstraintValidator<EnumIn, String> {

    private Class clazz;

    @Override
    public void initialize(EnumIn constraintAnnotation) {
        Class clazz = constraintAnnotation.enumType();
        this.clazz = clazz;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(StringUtils.isEmpty(value)) {
            return true;
        }
        Method method = null;
        Object result = null;
        try {
            method = clazz.getMethod("values");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        if (null != method) {
            try {
                result = method.invoke(null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        if (null != result) {
            EnumVerifiable[] enumVerifiables = (EnumVerifiable[]) result;
            for (EnumVerifiable enumVerifiable : enumVerifiables) {
                if (enumVerifiable.getName().equals(value)) {
                    return true;
                }
            }
        }
        return false;
    }
}
